package com.greet.mapper;

import com.greet.dto.OrdersPageQueryDTO;
import com.greet.entity.Orders;
import com.greet.vo.OrderStatisticsVO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Mapper
public interface OrdersMapper {
    Long insert(Orders orders);

    Long updateByNumber(Orders orders);

    @Select("select *" +
            " from orders where id = #{id}")
    Orders selectById(Long id);

    List<Orders> selectPageQuery(OrdersPageQueryDTO ordersPageQueryDTO);

    @Select("select count(0) from orders where user_id=#{userId}")
    Long countByUser(Long userId);

    @Update("update orders " +
            "set status=#{status}, cancel_reason=#{cancelReason}, rejection_reason=#{rejectionReason}, cancel_time=#{cancelTime} " +
            "where id=#{id}")
    void updateCancel(Orders orders);

    @Update("update orders " +
            "set status = 6, cancel_reason=#{cancelReason}, cancel_time = now() " +
            "where status = 1 and order_time < #{localDateTime}")
    void updateCancelByTimeoutOrder(LocalDateTime localDateTime, String cancelReason);


    @Update("update orders set status = 5 where status = 4 and order_time < #{localDateTime}")
    void updateOnTaskByDeliveryOrder(LocalDateTime localDateTime);

    @Select("select count(0) from orders")
    Long countAll();


    Integer countByStatus(LocalDateTime begin, LocalDateTime end, Integer status);

    @Update("update orders set status = #{status} where id = #{id}")
    void updateStatus(Long id, Integer status);

    @Select("select id, number, status, user_id, address_book_id, order_time, checkout_time, pay_method, pay_status, amount, remark, phone, address, user_name, consignee, cancel_reason, rejection_reason, cancel_time, estimated_delivery_time, delivery_status, delivery_time, pack_amount, tableware_number, tableware_status " +
            "from orders where number = #{number}")
    Orders selectByNumber(String number);

    @Select("select sum(amount) from orders " +
            "where order_time between #{begin} and #{end} and status=5")
    BigDecimal sumTurnoverByDate(LocalDateTime begin, LocalDateTime end);


    Integer count(LocalDateTime begin, LocalDateTime end, Integer status);

    @Select("select id\n" +
            "from orders\n" +
            "where order_time between #{begin} and #{end} and status = #{status}")
    List<Long> selectByTimeForId(LocalDateTime begin, LocalDateTime end, Integer status);

    BigDecimal averageAmount(LocalDateTime begin, LocalDateTime end, Integer status);
}
